package com.ruoyi.utils;

import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Title TODO
 * @Description TODO
 * @Author CAI ZHAI
 * @Date 2021/9/18 7:38
 **/
@Slf4j
public class ReflectUtil{
    /**
     * 根据属性名获取属性值
     **/
    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            return method.invoke(o, new Object[]{});
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 根据属性名设置属性值
     **/
    public static <T> void setFiledValue(Field field,Object value,T t) throws IllegalAccessException{
        if(field!=null){
            field.setAccessible(true);//修改作用域
            field.set(t,value);//设置值
        }
    }
    
    
}
